import { _decorator, Component, Node, view, ResolutionPolicy, screen, Size, Vec3, UITransform, Enum } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 屏幕适配缩放模式枚举
 */
export enum AdaptiveScaleMode {
    /** 保持宽度适配 */
    FIT_WIDTH = 0,
    /** 保持高度适配 */
    FIT_HEIGHT = 1,
    /** 等比缩放，保持内容完全可见 */
    SHOW_ALL = 2,
    /** 等比缩放，填满屏幕 */
    NO_BORDER = 3,
    /** 根据屏幕比例自动选择 */
    AUTO = 4
}

/**
 * 自适应屏幕缩放组件
 * 根据设计分辨率与实际屏幕分辨率的对比，对节点进行合理的等比缩放
 */
@ccclass('AdaptiveScreenScale')
export class AdaptiveScreenScale extends Component {

    @property({ type: Enum(AdaptiveScaleMode), tooltip: '缩放适配模式' })
    public scaleMode: AdaptiveScaleMode = AdaptiveScaleMode.AUTO;

    @property({ tooltip: '设计宽度（像素）' })
    public designWidth: number = 1334;

    @property({ tooltip: '设计高度（像素）' })
    public designHeight: number = 750;

    @property({ tooltip: '最小缩放比例' })
    public minScale: number = 0.5;

    @property({ tooltip: '最大缩放比例' })
    public maxScale: number = 2.0;

    @property({ tooltip: '是否启用调试信息' })
    public enableDebug: boolean = false;

    private _originalScale: Vec3 = new Vec3();
    private _screenSize: Size = new Size();
    private _designSize: Size = new Size();

    onLoad() {
        // 保存节点原始缩放
        this._originalScale.set(this.node.scale);

        // 设置设计尺寸
        this._designSize.set(this.designWidth, this.designHeight);

        // 初始化适配
        this.updateAdaptiveScale();

        // 监听屏幕尺寸变化
        view.on('canvas-resize', this.onScreenResize, this);
    }

    onDestroy() {
        view.off('canvas-resize', this.onScreenResize, this);
    }

    /**
     * 屏幕尺寸变化回调
     */
    private onScreenResize() {
        this.updateAdaptiveScale();
    }

    /**
     * 更新自适应缩放
     */
    public updateAdaptiveScale() {
        // 获取当前屏幕尺寸
        this._screenSize = screen.windowSize;

        // 计算缩放比例
        const scale = this.calculateScale();

        // 应用缩放
        this.applyScale(scale);

        if (this.enableDebug) {
            this.logDebugInfo(scale);
        }
    }

    /**
     * 计算缩放比例
     */
    private calculateScale(): number {
        const screenWidth = this._screenSize.width;
        const screenHeight = this._screenSize.height;

        const scaleX = screenWidth / this.designWidth;
        const scaleY = screenHeight / this.designHeight;

        let finalScale = 1.0;

        switch (this.scaleMode) {
            case AdaptiveScaleMode.FIT_WIDTH:
                finalScale = scaleX;
                break;

            case AdaptiveScaleMode.FIT_HEIGHT:
                finalScale = scaleY;
                break;

            case AdaptiveScaleMode.SHOW_ALL:
                finalScale = Math.min(scaleX, scaleY);
                break;

            case AdaptiveScaleMode.NO_BORDER:
                finalScale = Math.max(scaleX, scaleY);
                break;

            case AdaptiveScaleMode.AUTO:
                // 根据屏幕宽高比自动选择适配模式
                const screenRatio = screenWidth / screenHeight;
                const designRatio = this.designWidth / this.designHeight;

                if (screenRatio > designRatio) {
                    // 屏幕更宽，按高度适配
                    finalScale = scaleY;
                } else {
                    // 屏幕更高，按宽度适配
                    finalScale = scaleX;
                }
                break;
        }

        // 限制缩放范围
        finalScale = Math.max(this.minScale, Math.min(this.maxScale, finalScale));

        return finalScale;
    }

    /**
     * 应用缩放到节点
     */
    private applyScale(scale: number) {
        const newScale = new Vec3(
            this._originalScale.x * scale,
            this._originalScale.y * scale,
            this._originalScale.z
        );

        this.node.setScale(newScale);
    }

    /**
     * 获取当前的缩放比例
     */
    public getCurrentScale(): number {
        return this.node.scale.x / this._originalScale.x;
    }

    /**
     * 获取屏幕与设计尺寸的比率信息
     */
    public getScreenRatioInfo(): { screenRatio: number, designRatio: number, scaleX: number, scaleY: number; } {
        const screenWidth = this._screenSize.width;
        const screenHeight = this._screenSize.height;

        return {
            screenRatio: screenWidth / screenHeight,
            designRatio: this.designWidth / this.designHeight,
            scaleX: screenWidth / this.designWidth,
            scaleY: screenHeight / this.designHeight
        };
    }

    /**
     * 手动设置缩放模式并更新
     */
    public setScaleMode(mode: AdaptiveScaleMode) {
        this.scaleMode = mode;
        this.updateAdaptiveScale();
    }

    /**
     * 手动设置设计尺寸并更新
     */
    public setDesignSize(width: number, height: number) {
        this.designWidth = width;
        this.designHeight = height;
        this._designSize.set(width, height);
        this.updateAdaptiveScale();
    }

    /**
     * 重置为原始缩放
     */
    public resetToOriginalScale() {
        this.node.setScale(this._originalScale);
    }

    /**
     * 输出调试信息
     */
    private logDebugInfo(scale: number) {
        const ratioInfo = this.getScreenRatioInfo();
        console.log('=== AdaptiveScreenScale Debug Info ===');
        console.log(`Screen Size: ${ this._screenSize.width } x ${ this._screenSize.height }`);
        console.log(`Design Size: ${ this.designWidth } x ${ this.designHeight }`);
        console.log(`Screen Ratio: ${ ratioInfo.screenRatio.toFixed(3) }`);
        console.log(`Design Ratio: ${ ratioInfo.designRatio.toFixed(3) }`);
        console.log(`Scale X: ${ ratioInfo.scaleX.toFixed(3) }`);
        console.log(`Scale Y: ${ ratioInfo.scaleY.toFixed(3) }`);
        console.log(`Final Scale: ${ scale.toFixed(3) }`);
        console.log(`Scale Mode: ${ AdaptiveScaleMode[this.scaleMode] }`);
        console.log('=====================================');
    }
}

/**
 * 自适应屏幕缩放工具类
 * 提供静态方法用于快速适配
 */
export class AdaptiveScreenUtils {

    /**
     * 为节点添加自适应缩放组件
     */
    static addAdaptiveScale(node: Node, options?: {
        scaleMode?: AdaptiveScaleMode,
        designWidth?: number,
        designHeight?: number,
        minScale?: number,
        maxScale?: number;
    }): AdaptiveScreenScale {
        let component = node.getComponent(AdaptiveScreenScale);
        if (!component) {
            component = node.addComponent(AdaptiveScreenScale);
        }

        if (options) {
            if (options.scaleMode !== undefined) component.scaleMode = options.scaleMode;
            if (options.designWidth !== undefined) component.designWidth = options.designWidth;
            if (options.designHeight !== undefined) component.designHeight = options.designHeight;
            if (options.minScale !== undefined) component.minScale = options.minScale;
            if (options.maxScale !== undefined) component.maxScale = options.maxScale;
        }

        return component;
    }

    /**
     * 计算指定尺寸下的缩放比例
     */
    static calculateScaleForSize(designWidth: number, designHeight: number, mode: AdaptiveScaleMode = AdaptiveScaleMode.AUTO): number {
        const screenSize = screen.windowSize;
        const scaleX = screenSize.width / designWidth;
        const scaleY = screenSize.height / designHeight;

        switch (mode) {
            case AdaptiveScaleMode.FIT_WIDTH:
                return scaleX;
            case AdaptiveScaleMode.FIT_HEIGHT:
                return scaleY;
            case AdaptiveScaleMode.SHOW_ALL:
                return Math.min(scaleX, scaleY);
            case AdaptiveScaleMode.NO_BORDER:
                return Math.max(scaleX, scaleY);
            case AdaptiveScaleMode.AUTO:
                const screenRatio = screenSize.width / screenSize.height;
                const designRatio = designWidth / designHeight;
                return screenRatio > designRatio ? scaleY : scaleX;
            default:
                return 1.0;
        }
    }
}
